//
//  TripListVC.swift
//  ImGuider X
//
//  Created by 陆涛 on 2018/9/28.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit
import MJRefresh

class TripListVC: BaseVC {

    var layout: CarouselViewLayout!
    
    var collectionView: UICollectionView!
    
    var complete:((Trip?)->Void)?
    
    var viewmodel: TripListViewModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupData()
    }
    
    private func setupUI() {
        
        layout = CarouselViewLayout(anim: .carousel3)
        layout.scrollDirection = .vertical
        layout.visbleCount = 8
        
        let width = UIScreen.main.bounds.width - 40
        let height = CGFloat( width * 9 / 16) + 20
        layout.itemSize = CGSize(width: width, height: height)
        
        collectionView = UICollectionView(frame:UIScreen.main.bounds, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.groupTableViewBackground
        collectionView.dataSource = self
        collectionView.delegate = self
        self.view.addSubview(collectionView)
        
        collectionView.register(UINib(nibName: "TripListCCell", bundle: nil), forCellWithReuseIdentifier: "TripListCCell")
        collectionView.register(UINib(nibName: "TripListHeadView", bundle: nil), forSupplementaryViewOfKind: "TripListHeadView", withReuseIdentifier: "TripListHeadView")

        self.closeAutomaticallyInsets(scrollview: collectionView)
        
        let rightItem = UIBarButtonItem(image: UIImage(named:"加号"), style: .plain, target: self, action: #selector(scanAction))
        
        self.navigationItem.rightBarButtonItem = rightItem
        
        self.collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.viewmodel.reloadData()
        })
        
        let top = -(CGFloat(kScreenHeight) / 2 - height)
        
        self.collectionView.mj_header.ignoredScrollViewContentInsetTop = top
    }
    
    @objc private func scanAction() {
        
        let scanVC = ScanVC()
        scanVC.complete = {
            
            [weak self] tripid in
            guard let `self` = self else { return }
            
            if let trip = TripManager.share.hasBindTrip(tripid) {
                
                if let name = trip.planName {
                    
                    let str = String.localizedStringWithFormat(LocalizedString("qrcode_binded"), name)
                    
                    self.view.makeToast(str)
                }
            } else {
                
                self.viewmodel.bindTrip(tripid: tripid)
            }
        }
        
        self.navigationController?.pushViewController(scanVC, animated: true)
    }
    
    private func setupData() {
        
        title = LocalizedString("my_history_trips")
        
        viewmodel = TripListViewModel()
        
        if viewmodel.dataSource?.count == 0 {
            
            viewmodel.reloadData()
        }
        
        viewmodel.loadFinished = {
            
            [weak self] errmsg in
            guard let `self` = self else { return }
            
            self.makeToast(text: errmsg)
            self.collectionView.reloadData()
            self.collectionView.mj_header.endRefreshing()
        }

    }
}

extension TripListVC: UICollectionViewDataSource, UICollectionViewDelegate {
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewmodel.dataSource?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TripListCCell", for: indexPath) as! TripListCCell
        
        let trip = viewmodel.dataSource?[indexPath.row]
        
        cell.trip = trip
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let trip = viewmodel.dataSource?[indexPath.row]
        
        TripManager.share.lasttripid = trip?.orderId
        
        complete?(trip)
        
        if let _ = self.presentingViewController {
            
            self.dismiss(animated: true, completion: nil)
        } else {
            
            self.navigationController?.popViewController(animated: true)
        }
    }
}
